﻿<?php

class XmlTable2HTMLTable
{
	static public function ConvertText($xmltext,$params,&$ModPrice)
	{
		$title = '';
		$result = "";
		$tblResult = array();
		
		$tableAttrs	= (isset($params['TABLE'])) ? XmlTable2HTMLTable::_renderAtributes($params['TABLE']) : "";
		
		$trClass = "";
		if ($params!=null)
		{
			if (isset($params['TR']) && isset($params['TR']['class'])){$trClass = $params['TR']['class']; unset($params['TR']['class']); }
			$trAttrs = (isset($params['TR'])) ? XmlTable2HTMLTable::_renderAtributes($params['TR']) : "";
			if ($trClass!="") $params['TR']['class'] = $trClass;
			$trClass = "";
			$tdAttrs = (isset($params['TD'])) ? XmlTable2HTMLTable::_renderAtributes($params['TD']) : "";
		}
		else
		{
			$params = array();
			$trAttrs = '';
			$tdAttrs = '';
		}
		
		$xmltext = utf8_encode($xmltext);
		$xml = new XMLReader();
		$xml->XML($xmltext);
		
		$wait_text = false;
		$areAllStrings = true;
		$isTableOpened = false;
		$isTROpened = false;
		$isTDOpened = false;
		$rowCnt = 0;
		
		$row = "";
		
		while($xml->read())
		{
			if ($xml->nodeType == XMLReader::ELEMENT)
			{
				$name = strtolower($xml->name);
				if ($name==='worksheet')
				{
					$title = utf8_decode($xml->getAttribute('ss:Name'));
				}
				elseif ($name==='table')
				{
					$result.="<!-- @@@@TABLE_BEGIN@@@ -->";
					$result.="<table".$tableAttrs;
					if ($title!='') $result.=' title="'.$title.'"';
					$result.='>';
					
					$isTableOpened = true;
				}
				elseif ($name==='row')
				{
					$rowCnt++;
					$result.="<tr".$trAttrs;
					$n = ($rowCnt%2)==0 ? 'classOdd' : 'classEven';
					if (isset($params['TR']) && isset($params['TR']['class'])) $trClass = $params['TR']['class'];
					if (isset($params[$n]))
					{
						if ($trClass!="") $trClass .= " ";
						$trClass.= $params[$n];
					}
					if ($trClass!="") $result.= ' class="'.$trClass.'"';
					$trClass = "";
					$result.=">";
					$isTROpened = true;
					$row = "";
				}
				elseif ($name==='cell')
				{
					$row .="<td".$tdAttrs;
					if ($xml->hasAttributes) 
					{
						$rowspan = $xml->getAttribute('ss:MergeDown');
						$colspan = $xml->getAttribute('ss:MergeAcross');
						if ($rowspan!="") {$rowspan++; $row .=" rowspan=\"{$rowspan}\"";}
						if ($colspan!="") {$colspan++; $row .=" colspan=\"{$colspan}\"";}
					}
					$row .=">";
					$isTDOpened = true;
				}
				elseif ($name==='data')
				{
					$wait_text = true;
					$type = strtolower($xml->getAttribute('ss:Type'));
					$areAllStrings = $areAllStrings && ($type=='string');
				}		
			}
			elseif (($xml->nodeType===XMLReader::TEXT)&& $wait_text)
			{
				$cellVal = utf8_decode($xml->value);
				while (true)
				{
					$p = strpos($cellVal,'{$');
					if ($p!==false)
					{
						$p1 = strpos($cellVal,'.',$p);
						if ($p1!==false)
						{
							$article = substr($cellVal,$p+2,$p1-$p-2);
							$p2 = strpos($cellVal,'}',$p1);
							if ($p2!==false)
							{
								$attribute = substr($cellVal,$p1+1,$p2-$p1-1);
								//echo $article.'-'.$attribute;
								$v = $ModPrice->price->GetAttributeByArticle($article,$attribute);
								if (is_numeric($v)) $areAllStrings = false;
								$v = str_replace('.00','',$v);
								//echo $v;
								$cellVal = str_replace('{$'.$article.'.'.$attribute.'}',$v,$cellVal);
							}
						}
					}
					else
						break;
				}
				
				//$cellVal
				
				$row .= $cellVal;//utf8_decode($xml->value);
				//$row .=$xml->value;
				$wait_text = false;
			}
			elseif ($xml->nodeType == XMLReader::END_ELEMENT)
			{
				$name = strtolower($xml->name);
				if ($name==='cell')
				{
					$isTDOpened = false;
					$row.="</td>";
				}
				elseif ($name==='row')
				{
					$isTROpened = false;
					if ( isset($params['useTH']) && ($params['useTH']==1) && $areAllStrings) 
					{
						$row = str_replace("<td","<th",$row);
						$row = str_replace("</td>","</th>",$row);
					}
					$result.=$row."</tr>";
					$areAllStrings = true;
				}
				elseif ($name==='table')
				{
					$isTableOpened = false;
					$result.="</table><!-- @@@@TABLE_END@@@ -->";
				}
				elseif ($name==='worksheet')
				{
					$tblResult[] = array( 'title'=>$title, 'table'=>$result);
					$title = '';
					$result = "";
				}
			}
		}
		//if (!$xml->isValid()) { echo "invalid"; return false;}
		$xml->close();		
		if ($isTableOpened || $isTROpened || $isTDOpened) return false;
		return $tblResult;//array( 'title'=>$title, 'table'=>$result);
	}
	
	static public function ConvertFile($filename,$params,&$ModPrice)
	{
		$f = fopen ($filename,'r');
		$size = filesize($filename);
		$buf = fread($f,$size);
		//$buf = iconv("UTF-8", "cp1251", $buf );//ISO-8859-1
		fclose($f);
		return XmlTable2HTMLTable::ConvertText($buf,$params,$ModPrice);
	}
	
	static public function ConvertTextToArray($xmltext)
	{
		$result = "";
		$tblResult = array();
		$title = '';
		$rows = array();
		$cells = array();
		
		$xmltext = utf8_encode($xmltext);
		$xml = new XMLReader();
		$xml->XML($xmltext);
		
		$wait_text = false;
		$isTableOpened = false;
		$isTROpened = false;
		$isTDOpened = false;
		
		while($xml->read())
		{
			if ($xml->nodeType == XMLReader::ELEMENT)
			{
				$name = strtolower($xml->name);
				if ($name==='worksheet')
				{
					$title = utf8_decode($xml->getAttribute('ss:Name'));
					$rows = array();
				}
				elseif ($name==='table')
				{					
					$isTableOpened = true;
				}
				elseif ($name==='row')
				{
					$cells = array();
					$isTROpened = true;
				}
				elseif ($name==='cell')
				{
					$rowspan = 1;
					$colspan = 1;
					if ($xml->hasAttributes) 
					{
						$rowspan = $xml->getAttribute('ss:MergeDown');
						$colspan = $xml->getAttribute('ss:MergeAcross');
						$rowspan = ($rowspan=="")? 1 : $rowspan+1;
						$colspan = ($colspan=="")? 1 : $colspan+1;
					}
					$cells[] = array('',$colspan,$rowspan);
					$isTDOpened = true;
				}
				elseif ($name==='data')
				{
					$wait_text = true;
					$type = strtolower($xml->getAttribute('ss:Type'));
					$cells[count($cells)-1][3] = $type;
				}		
			}
			elseif (($xml->nodeType===XMLReader::TEXT)&& $wait_text)
			{
				$cells[count($cells)-1][0] =utf8_decode($xml->value);
				$wait_text = false;
			}
			elseif ($xml->nodeType == XMLReader::END_ELEMENT)
			{
				$name = strtolower($xml->name);
				if ($name==='cell')
				{
					$isTDOpened = false;
				}
				elseif ($name==='row')
				{
					$isTROpened = false;
					$rows[] = $cells;
				}
				elseif ($name==='table')
				{
					$isTableOpened = false;
				}
				elseif ($name==='worksheet')
				{
					$tblResult[] = array( 'title'=>$title, 'rows'=>$rows);
					$title = '';
				}
			}
		}
		//if (!$xml->isValid()) { echo "invalid"; return false;}
		$xml->close();		
		if ($isTableOpened || $isTROpened || $isTDOpened) return false;
		return $tblResult;//array( 'title'=>$title, 'table'=>$result);
	}
	
	static public function ConvertFileToArray($filename)
	{
		$f = fopen ($filename,'r');
		$size = filesize($filename);
		$buf = fread($f,$size);
		$buf = iconv("UTF-8", "cp1251", $buf );//ISO-8859-1
		fclose($f);
		return XmlTable2HTMLTable::ConvertTextToArray($buf);
	}
	
	static public function ValidateText($xmltext)
	{
		$result = "";
		$xmltext = utf8_encode($xmltext);
		$pos = strpos($xmltext,'<?mso-application progid="Excel.Sheet"?>');
		if (strpos($xmltext,'<?mso-application progid="Excel.Sheet"?>')===false) { return false;}
		return true;
	}
	
	static public function ValidateFile($filename)
	{
		$f = fopen ($filename,'r');
		$size = filesize($filename);
		$buf = fread($f,$size);
		fclose($f);
		return XmlTable2HTMLTable::ValidateText($buf);
	}
	
	private static function _renderAtributes($attrArr)
	{
		$attrs = array();
		foreach ($attrArr as $attrName => $attrValue) {
			$attrs[] = $attrName.'="'.$attrValue.'"';
		}
		if (count($attrs>0)) $attrsStr = " ".implode(" ",$attrs); else $attrsStr="";
		return $attrsStr;
	}
}
?>
